const app = getApp();
let province, city, area;
const CONFIRM_TEXT = "确认充值";
const APPLY_TEXT = "申请";
const localRechargeConfig = [20, 50, 100, 120, 150, 200]
Page({
  data: {


    showCard: false, //true充值 false开卡
    custom: false,
    btnTxt: APPLY_TEXT,
    isShow: true,

    cardInfo: "", //查询到的水卡信息
    userInfo: {},
    balance: 0, //充值账户余额
    card_number: "", //卡号
    deposits: [], //押金设置
    depositIndex: 0,
    all_url_arrs: [],
    url_arrs: [],
    max_count_img: 2,
    cardType: [], //水卡类型
    cardTypeIndex: '',
    credentialType: [], //证件类型
    credentialTypeIndex: 0,
    recharge: [], //充值金额配置
    rechargeIndex: 0,
    auditList: ['年审', '月审', "不定期"], //审核类型
    auditIndex: 0,
    customMoney: 0, //自定义金额
    custom: false,
    full_name: "",
    tel: "",
    village_name: "",
    village_id: "",
    idcard: '', //证件号码
    address: '',
    remark: '',
  },

  onLoad: function (options) {
    this.pageType = options.type || 1; //1开卡  2充值
    wx.setNavigationBarTitle({
      title: this.pageType == 1 ? '特殊水卡开卡' : '特殊水卡充值'
    })

    this.setData({
      isShow: this.pageType == 2 ? false : true,
      btnTxt: this.pageType == 1 ? APPLY_TEXT : CONFIRM_TEXT,
      recharge: localRechargeConfig
    })
    this.getBalance();
    this.getDeposits();
    this.getCardType();
    this.getCredentialType();
    this.getSpecialCardRechargeConfig();

    let _self = this;
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on("acceptDataFromWaterRecharge", function (data) {
      //从水卡充值界面跳转过来
      _self.setData({
        card_number: app.formatCard(data.card_number)
      })
      _self.getWaterCard(app.trimAll(_self.data.card_number));
    });

  },

  //获取水卡类型
  getCardType() {
    app.ajax({
      url: "Partner/WaterCard/getCarType",
      data: {
        type: 2,
        is_apply: 1
      },
      success: res => {
        if (res.data.code > 0) {
          this.setData({
            cardType: res.data.data
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  },

  //获取证件类型
  getCredentialType() {
    app.ajax({
      url: "Partner/WaterCard/getCredentialType",
      success: res => {
        if (res.data.code > 0) {
          this.setData({
            credentialType: res.data.data
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  },

  //获取特殊水卡充值配置
  getSpecialCardRechargeConfig() {
    app.ajax({
      url: "Partner/WaterCard/getSpecialCardRechargeConfig",
      success: res => {
        if (res.data.code > 0) {
          this.setData({
            recharge: this.pageType == 1 ? res.data.data : localRechargeConfig
          })
          this.serveRechargeConfig = res.data.data;
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast("网络错误");
      }
    })
  },

  cardTypeChange(e) {
    this.setData({
      cardTypeIndex: e.detail.value
    })
  },

  auditChange(e) {
    this.setData({
      auditIndex: e.detail.value
    })
  },

  credentialTypeChange(e) {
    this.setData({
      credentialTypeIndex: e.detail.value
    })
  },


  hideCustom() {
    this.setData({
      custom: false
    })
  },
  chooseDeposit(e) {
    this.setData({
      depositIndex: e.currentTarget.dataset.index
    })
  },

  rechargeChange(e) {
    this.setData({
      rechargeIndex: e.currentTarget.dataset.index
    })
  },

  rechargeCustom(e) {
    this.setData({
      rechargeIndex: -1,
      custom: true
    })
  },

  customMoneyInput(e) {
    this.setData({
      customMoney: e.detail.value
    })
  },





  //选择园区
  chooseVillage() {
    let _self = this;
    wx.navigateTo({
      url: '../choiceCommunity/choiceCommunity',
      events: {
        acceptDataFromOpenedPage: function (village) {
          let village_name = village.village_name;
          _self.setData({
            village_name,
            village_id: village.id,
            address: village.address,
          })
          province = village.province;
          city = village.city;
          area = village.area;
        }
      },
      success: function (res) {
        res.eventChannel.emit('acceptDataFromOpenerPage', {
          village_id: _self.data.village_id
        })
      }
    })
  },




  handleInputCardNumber(e) {
    const value = e.detail.value;
    let data = {
      card_number: value,
    }
    if (value.trim() === "") {
      Object.assign(data, {
        cardInfo: "",
        showCard: false,
        isShow: this.pageType == 1 ? true : false,
        btnTxt: this.pageType == 1 ? APPLY_TEXT : CONFIRM_TEXT,
        recharge: this.pageType == 1 ? this.serveRechargeConfig : localRechargeConfig
      })
      if (this.data.cardInfo) {
        Object.assign(data, {
          tel: "",
          full_name: "",
          village_name: "",
        })
      }
      this.setData(data)
    } else {
      this.setData({
        card_number: app.formatCard(value)
      })
    }
  },

  handleInput(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },



  //获取合伙人账户余额
  getBalance() {
    app.ajax({
      url: "Partner/WaterCard/getPartnerQuota",
      success: res => {
        if (res.data.code == 1000) {
          this.setData({
            userInfo: res.data.data,
            balance: res.data.data.special_recharge_balance
          })
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        app.showToast("网络错误")
      }
    })
  },


  //获取押金配置
  getDeposits() {
    app.ajax({
      url: "Common/Common/cardDeposit",
      success: res => {
        if (res.data.code == 1000) {
          this.setData({
            deposits: res.data.data
          })
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        app.showToast("网络错误")
      }
    })
  },



  //获取水卡数据
  getWaterCard(card_number, isLoading = true) {
    isLoading && wx.showLoading({
      mask: true
    })
    app.ajax({
      url: "Partner/WaterCard/getWaterCard",
      data: {
        card: card_number
      },
      success: res => {
        isLoading && wx.hideLoading();
        const source = res.data;
        if (source.code > 0) {
          this.setData({
            showCard: true,
            cardInfo: source.data,
            full_name: source.data.full_name || "",
            tel: source.data.tel || '',
            village_name: source.data.village_name || '',
            village_id: source.data.village_id || '',
            btnTxt: CONFIRM_TEXT,
            isShow: source.data.is_special== 2 ? true : false,
            recharge: localRechargeConfig
          })
        } else {
          const obj = {
            cardInfo: "",
            showCard: false,
            btnTxt: APPLY_TEXT,
            isShow: true,
            recharge: this.serveRechargeConfig
          }
          if (this.data.cardInfo) {
            Object.assign(obj, {
              tel: "",
              full_name: "",
              village_name: "",
              village_id: "",
            })
          }
          this.setData(obj)
        }
      },
      error: e => {
        isLoading && wx.hideLoading();
        app.showToast("网络错误");
      }
    })
  },



  //根据卡号去查询水卡信息 存在为充值操作，反之为开卡操作
  fetchUserCard(e) {
    let card_number = app.trimAll(e.detail.value);
    if (card_number !== "") {
      this.getWaterCard(card_number);
    }
  },


  //扫码操作
  scanCode() {
    wx.scanCode({
      success: res => {
        res.result && this.setData({
          card_number: app.formatCard(res.result)
        })
        const card_number = app.trimAll(res.result);
        if (card_number === "") {
          app.showToast("请扫描正确的水卡号");
        } else {
          this.getWaterCard(card_number);
        }
      },
      fail: error => {
        console.log(error)
      }
    })
  },



  //提交数据
  handleSubmit() {
    let param = {};
    const card_number = app.trimAll(this.data.card_number);
    if (card_number == "") {
      app.showToast("请输入卡号");
      return;
    }
    if (this.data.isShow) {
      if (this.data.village_name === '') {
        app.showToast("请选择园区");
        return;
      }
      if (this.data.cardTypeIndex === '') {
        app.showToast("请选择水卡类型");
        return;
      }
      if (this.data.full_name === '') {
        app.showToast("请输入姓名");
        return;
      }
      if (this.data.tel === '') {
        app.showToast("请输入手机号码");
        return;
      }
      if (this.data.idcard === '') {
        app.showToast("请输入证件号码");
        return;
      }
      if (this.data.url_arrs.length <= 0) {
        app.showToast("请上传证件照片");
        return;
      }
      let price = 0;
      if (this.data.rechargeIndex !== -1) {
        price = this.data.recharge[this.data.rechargeIndex];
      } else {
        price = this.data.customMoney;
      }
      Object.assign(param, {
        full_name: this.data.full_name,
        tel: this.data.tel,
        card_class: 2,
        card_type: this.data.cardType[this.data.cardTypeIndex].id,
        paper_type: this.data.credentialType[this.data.credentialTypeIndex].id,
        IDcard: this.data.idcard,
        sn: card_number,
        address: this.data.address,
        village_name: this.data.village_name,
        card_price: price,
        deposit: this.data.deposits[this.data.depositIndex],
        audit_data: this.data.url_arrs,
        audit_type: parseInt(this.data.auditIndex) + 1,
      })
    } else {
      let price;
      if (this.data.rechargeIndex !== -1) {
        price = this.data.recharge[this.data.rechargeIndex];
      } else {
        if (this.data.customMoney <= 0) {
          app.showToast("自定义金额必须大于0");
          return;
        }
        price = this.data.customMoney;
      }
      if (this.data.remark == "") {
        app.showToast("请填写备注");
        return;
      }
      Object.assign(param, {
        card: card_number,
        money: price,
        type: 3,
        remake: this.data.remark
      })
    }
    wx.showModal({
      title: '提示',
      content: !this.data.isShow ? `是否充值？` : `是否开卡？`,
      success: res => {
        if (res.confirm) {
          console.log(param, "param");
          this.excute(param);
        }
      }
    })
  },


  excute(param) {
    wx.showLoading({
      mask: true,
    })
    let url = 'Partner/WaterCard/auditSpecialCard';
    if (!this.data.isShow) {
      url = "Partner/WaterCard/waterCardRecharge";
    }
    app.ajax({
      url,
      method: "POST",
      data: param,
      success: res => {
        wx.hideLoading()
        var flag = res.data;
        if (flag.code > 0) {
          app.showToast(flag.message, "success");
          let resetData = { //需要重置的数据
            rechargeIndex: 0,
            customMoney: 0,
          }
          if (this.pageType == 1) {
            Object.assign(resetData, {
              showCard: false,
              card_number: '',
              full_name: "",
              tel: "",
              cardInfo: "",
              isShow: true,
              village_name: '',
              village_id: "",
              address: '',
              idcard: '',
              depositIndex: 0,
              credentialTypeIndex: 0,
              cardTypeIndex: '',
              auditIndex: 0,
              customMoney: 0,
              all_url_arrs: [],
              url_arrs: [],
              btn: APPLY_TEXT,
              recharge: this.serveRechargeConfig
            })
          } else {
            Object.assign(resetData, {
              remark: '',
              btn: CONFIRM_TEXT,
              isShow: false,
              recharge: localRechargeConfig
            });
            this.getWaterCard(app.trimAll(this.data.card_number), false)
          }
          this.setData(resetData)
          wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
          })
          this.getBalance();
        } else {
          app.showToast(flag.message)
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网络错误")
      }
    })

  },




  excutePost(param) {
    Object.assign(param, {
      full_name: this.data.full_name,
      tel: this.data.tel,
      village_name: this.data.village_name,
      village_id: this.data.village_id,
      card: app.trimAll(this.data.card_number),
      money: this.data.money,
      give: this.data.give,
      template_id: this.data.moneyIndex == -1 || (this.data.showCard == false && this.data.money == 0) ? '' : this.data.template_id,
      promotion_id: this.promotion_id
    })
    wx.showLoading({
      mask: true,
    })
    app.ajax({
      url,
      method: "POST",
      data: param,
      success: res => {
        wx.hideLoading()
        var flag = res.data;
        if (flag.code > 0) {
          app.showToast(flag.message, "success");
          let resetData = { //需要重置的数据
            rechargeIndex: '',
          }
          if (!this.data.showCard) {
            Object.assign(resetData, {
              showCard: false,
              card_number: '',
              full_name: "",
              tel: "",
              cardInfo: "",
              isShow: true,
              btnTxt: APPLY_TEXT,
              promotions: [],
              village_name: '',
              village_id: "",
              address: '',
              idcard: '',
              depositIndex: 0,
              credentialTypeIndex: 0,
              cardTypeIndex: '',
              auditIndex: 0,
              customMoney: 0,
              all_url_arrs: [],
              url_arrs: [],
            })
          } else {
            this.getWaterCard(app.trimAll(this.data.card_number), false)
          }
          this.setData(resetData)
          wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
          })
          this.getBalance();
        } else {
          app.showToast(flag.message)
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网络错误")
      }
    })
  },



  chooseImg() {
    let pictrues = this.data.all_url_arrs;
    let count = this.data.max_count_img - pictrues.length;
    wx.chooseImage({
      sizeType: ["compressed"],
      count,
      success: res => {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '资源上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          this.uploadFile(tempFilePaths[i], i, tempFilePaths.length - 1);
        }
      }
    })
  },

  uploadFile: function (tempFilePath, i, len) {
    var that = this;
    wx.uploadFile({
      url: app.globalData._url + 'Common/Common/upload',
      filePath: tempFilePath,
      name: 'file',
      success(res) {
        var source = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}");
        if (source.code == 1000) {
          let all_url_arrs = that.data.all_url_arrs;
          let url_arrs = that.data.url_arrs;
          url_arrs.unshift(source.data.url);
          all_url_arrs.unshift(source.data.all_url);
          console.log(all_url_arrs, url_arrs);
          if (i == len) {
            wx.hideLoading();
          }
          that.setData({
            all_url_arrs,
            url_arrs
          })
        } else {
          app.showToast(`第${i+1}张图片上传失败`);
        }
      }
    })
  },

  deleteImg(e) {
    const index = e.currentTarget.dataset.index;
    let all_url_arrs = this.data.all_url_arrs;
    let url_arrs = this.data.url_arrs;
    all_url_arrs.splice(index, 1)
    url_arrs.splice(index, 1)
    this.setData({
      all_url_arrs,
      url_arrs
    })
  },
})